package com.bungarus.device.model;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeviceServiceImpl  {
    Logger logger = Logger.getLogger(DeviceServiceImpl.class);

    private JdbcTemplate jdbcTemplate;

    @Autowired
    private DeviceServiceImpl(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * register device when user logged in
     * if the same device type exists, compare the device name, if is not identical, update it with new one
     */
    public int registerDevice(Device device) {
        logger.info("client message received: " + device);

        //check if device already exists
        StringBuilder sb = new StringBuilder("select name " +
                " from t_device " +
                " where tenantid=? and mid=? and type=? and app=?" +
                " and status=1 " +
                " limit 1");
        String querySql = sb.toString();
        String devName = null;
        try {
            devName = jdbcTemplate.queryForObject(querySql, new Object[]{device.getTenantId(), device.getMid(), device.getType(), device.getApp()}, String.class);
        }catch(EmptyResultDataAccessException e){
            logger.info("device not found.");
        }
        boolean insertNew = null == devName ? true : false;

        // if device already exists, and device name is different, then make the old one invalid
        if(null != devName && !devName.equals(device.getName())) {
            String sqlUpdate = "update t_device set status=0" +
                    " where tenantid=? and mid=? and app=? and type=?" +
                    " and status=1";
            jdbcTemplate.update(sqlUpdate, device.getTenantId(), device.getMid(), device.getApp(), device.getType());
            insertNew=true;
        }
        // if need to insert new record
        if(insertNew) {
            String sqlInsert = "insert into t_device  set tenantid=?, mid=?, app=?, type=?, name=?, status=1";
            jdbcTemplate.update(sqlInsert, device.getTenantId(), device.getMid(), device.getApp(), device.getType(), device.getName());
        }
        return 200;
    }

    /**
     * get all valid devices for specified member
     */
    public List<Device> getDeviceList(String tid, String app, String mid) {
        logger.info("client message received: " + tid + "," + app + "," + mid);

        StringBuilder sb = new StringBuilder("select tenantid as tid, mid, type, app, name " +
                " from t_device " +
                " where tenantid=? and mid=? and app=?" +
                " and status=1");
        String querySql = sb.toString();
        List<Device> deviceList = jdbcTemplate.query(querySql, new Object[]{tid, mid, app},
                (resultSet, rowNum) -> {
                    Device device = new Device();
                    device.setTenantId(resultSet.getString("tid"));
                    device.setMid(resultSet.getString("mid"));
                    device.setApp(resultSet.getString("app"));
                    device.setType(resultSet.getInt("type"));
                    device.setName(resultSet.getString("name"));
                    return device;
                });
        return deviceList;
    }

}
